// 全排列2

package Leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class solution_047 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] isUse = new boolean[nums.length];
        link(nums, isUse, 0, result, new ArrayList<>());
        return result;
    }

    public void link(int[] nums, boolean[] isUse, int length, List<List<Integer>> result, List<Integer> combination) {
        if (length == nums.length) {
            for (int i = 0; i < result.size(); i++)
                if (result.get(i).equals(new ArrayList<>() {
                    {
                        addAll(combination);
                    }
                }) == true)
                    return;
            result.add(new ArrayList<>() {
                {
                    addAll(combination);
                }
            });
        }
        for (int i = 0; i < nums.length; i++) {
            if (isUse[i] == false) {
                isUse[i] = true;
                combination.add(nums[i]);
                link(nums, isUse, length + 1, result, combination);
                combination.remove(combination.size() - 1);
                isUse[i] = false;
            }
        }
    }

}

public class Solution047 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        boolean[] isUse = new boolean[nums.length];
        link(nums, isUse, 0, result, new ArrayList<>());
        return result;
    }

    public void link(int[] nums, boolean[] isUse, int length, List<List<Integer>> result, List<Integer> combination) {
        if (length == nums.length) {
            result.add(new ArrayList<>(combination));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // 剪枝
            //情况一，数组中该数已经被使用
            //情况二，当与前面的数相同时，如果前面的数没有被使用，则跳过，保证顺序一定是从左至右
            if (isUse[i] == true || (i > 0 && nums[i] == nums[i - 1] && isUse[i - 1] == false))
                continue;
            isUse[i] = true;
            combination.add(nums[i]);
            link(nums, isUse, length + 1, result, combination);
            combination.remove(combination.size() - 1);
            isUse[i] = false;
        }
    }
}
